package com.kuqi.crs.web.Filter;

import com.kuqi.crs.settings.domain.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author:kuqi
 * @createTime:2021/9/24 16:48
 * @description:
 */
@WebFilter(filterName = "LoginFilter",value = {"*.do","*.jsp"})
public class LoginFilter implements Filter {
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        String path = request.getServletPath();
        HttpSession session = request.getSession();
        User user = (User)session.getAttribute("user");

        //不应该拦截的资源，自动放行
        if ("/login.jsp".equals(path) || "/settings/user/login.do".equals(path)){
            chain.doFilter(req,res);
        }else if(user != null){
            chain.doFilter(req,res);
        }else{//需要拦截重定向
            response.sendRedirect(request.getContextPath()+"/login.jsp");
        }
    }
}
